﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Robot1 : MonoBehaviour
{

    public GameObject xAxis;
    public GameObject yAxis;
    public GameObject zAxis;

    public GameObject origin;
    public GameObject point1;
    public GameObject point2;

    public List<Vector3> path;
    public bool isLoop = false;
    public AnimationCurve speedCurve;

    private Vector3 position;

    // x,y,z 的范围
    //[Range(-0.23f, 0.23f)]
    //public float x;
    //[Range(-0.2f, 0.15f)]
    //public float y;
    //[Range(-0.16f, 0.16f)]
    //public float z;
    //[Range(-0f, 5.0f)]

    void Start ()
    {
        position = Vector3.zero;
        //MoveTo(point1.transform.position - origin.transform.position, point2.transform.position - origin.transform.position);
        MoveOnPath(true);
    }

    /// <summary>
    /// 移动到一个目标点
    /// </summary>
    /// <param name="targetPos">目标点</param>
    public void MoveTo(Vector3 targetPos)
    {
        StartCoroutine(MoveToPosition(targetPos));
    }

    /// <summary>
    /// 先移动到一个目标点，在移动到下一个目标点
    /// </summary>
    /// <param name="targetPos1">目标点1</param>
    /// <param name="targetPos2">目标点2</param>
    public void MoveTo(Vector3 targetPos1, Vector3 targetPos2)
    {
        path.Clear();
        path.Add(targetPos1);
        path.Add(targetPos2);
        StartCoroutine(MoveOnPath(isLoop));
    }

    /// <summary>
    /// 按路径循环移动
    /// </summary>
    /// <param name="loop">是否循环</param>
    /// <returns></returns>
    IEnumerator MoveOnPath(bool loop = false)
    {
        do
        {
            foreach (var point in path)
                yield return StartCoroutine(MoveToPosition(point));
        }
        while (loop);
    }

    /// <summary>
    /// 移动到一个目标点
    /// </summary>
    /// <param name="target">目标点</param>
    /// <returns></returns>
    IEnumerator MoveToPosition(Vector3 target)
    {
        // TODO: 增加范围的控制
        while(position != target)
        {
            position = Vector3.MoveTowards(position, target, speedCurve.Evaluate(Mathf.Clamp01(Mathf.Abs(position.x - target.x))) * Time.deltaTime);
            xAxis.transform.position = new Vector3(position.x, xAxis.transform.position.y, xAxis.transform.position.z);
            yAxis.transform.position = new Vector3(yAxis.transform.position.x, position.y, yAxis.transform.position.z);
            zAxis.transform.position = new Vector3(zAxis.transform.position.x, zAxis.transform.position.y, position.z);
            yield return 0;
        }
    }
}
